﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using T.Materials.Repository.MaterialsImpl;
using T.Materials.Repository.MaterialsInterface;

namespace T.Materials.Read.API.Extension
{
    /// <summary>
    /// 静态扩展类
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 上下文扩展方法
        /// </summary>
        /// <typeparam name="TDbContext">上下文泛型类</typeparam>
        /// <param name="services">服务集合</param>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="enableSqlLog">是否启用sql日志</param>
        /// <returns></returns>
        public static IServiceCollection AddDbContextService<TDbContext>(this IServiceCollection services, string connectionString, bool enableSqlLog) where TDbContext : DbContext
        {
            //传入的上下文
            return services.AddDbContext<TDbContext>(builder =>
            {
                //默认使用微软sqlserver 可切换成MySQL、PostgreSQL等
                //connectionString为连接字符串
                builder.UseSqlServer(connectionString, action =>
                {
                    action.EnableRetryOnFailure(
                        //最大重试次数
                        maxRetryCount: 10,
                        //最大重试间隔时间
                        maxRetryDelay: TimeSpan.FromSeconds(60),
                        //是否在日志中显示失败的sql语句
                        errorNumbersToAdd: null);
                }).EnableSensitiveDataLogging();
                //enableSalLog为是否启用sql日志
                //只有在开发环境下才启用sql日志
                if (enableSqlLog)
                {
                    //启用sql日志
                    builder.UseLoggerFactory(LoggerFactory.Create(configure =>
                    {
                        //过滤日志
                        configure
                        .AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information)
                        //打印到控制台
                        .AddConsole();
                    }));
                }
            });
        }

        /// <summary>
        /// 仓储 扩展方法
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <returns></returns>
        public static IServiceCollection AddRepository(this IServiceCollection services)
        {
            //注册仓储
            services.AddScoped<IEconomizeRepository, EconomizeRepository>();
            services.AddScoped<ICountryRepository, CountryRepository>();
            services.AddScoped<IMaterialRequisitionRepository, MaterialRequisitionRepository>();
            services.AddScoped<IMaterialStatisticsRepository, MaterialStatisticsRepository>();
            services.AddScoped<IMaterialStoreRepository, MaterialStoreRepository>();
            services.AddScoped<IStorageMaterialsRepository, StorageMaterialsRepository>();
            services.AddScoped<IMApprow, Mapprow>();
            return services;
        }

        /// <summary>
        /// 注册JWT验证扩展方法
        /// </summary>
        /// <param name="dollection">服务集合</param>
        /// <param name="builder"></param>
        public static void AddJWT(this IServiceCollection collection, WebApplicationBuilder builder)
        {
            //  添加JWT验证        认证使用             配置                服务
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
            {

                // 私钥             字节数组       编码           配置         JwtTokenOptions            安全密钥
                var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["JwtTokenOptions:SecurityKey"]);
                // 验证参数         令牌验证参数      
                o.TokenValidationParameters = new TokenValidationParameters()
                {
                    // 验证发布者
                    ValidateIssuer = true,
                    // 发布者信息
                    ValidIssuer = builder.Configuration["JwtTokenOptions:Issuer"],

                    // 验证接收者
                    ValidateAudience = true,
                    // 接收者
                    ValidAudience = builder.Configuration["JwtTokenOptions:Audience"],

                    // 验证是否过期
                    ValidateLifetime = false,


                    // 验证私钥
                    IssuerSigningKey = new SymmetricSecurityKey(secretByte)

                };
            });
        }
    }
}
